package cn.bm.web.services;

import cn.bm.web.db.RedisConnectionPool;
import redis.clients.jedis.Jedis;
import spark.Request;
import spark.Response;

import java.util.UUID;

public class SessionManager {
    private static final String SESSION_PREFIX = "sessionId:";

    //设置session初始化
    public static String createSession(Request request, Response response,String username) {
        String sessionId = request.session().attribute("sessionId");
        if(sessionId == null) {
            sessionId = UUID.randomUUID().toString();
        }
        try (Jedis jedis = RedisConnectionPool.getConnection()) {
            jedis.set(SESSION_PREFIX + sessionId, username); // 可根据需要存储初始数据
            System.out.println("当前在creatSession:"+ jedis.get(SESSION_PREFIX + sessionId));
            request.session().attribute("sessionId", sessionId);
            System.out.println("cookie : " + request.cookie("sessionId"));
        }
        System.out.println("Created sessionId:" + sessionId + " username: " + username);
        return sessionId;
    }

    //得到
    public static String getSession(Request request) {
        String sessionId = request.session().attribute("sessionId");
        System.out.println("getSession : " + sessionId);
        if (sessionId != null) {
            try (Jedis jedis = RedisConnectionPool.getConnection()) {
                System.out.println("getSession查找的username:" + jedis.get(SESSION_PREFIX + sessionId));
                return jedis.get(SESSION_PREFIX + sessionId);
            }
        }
        return null;
    }
}